import { imager, loger } from '@daelui/dogjs/dist/components.js'

// 是否移动端
const isPlus = typeof plus === 'object' && typeof plus.io === 'object'

export function translateApp({ src, quality, maxSize, maxWidth, maxHeight } = {}, onsuccess, onerror) {
  quality = isNaN(quality) ? 50 : quality // 默认质量50
  quality = quality < 1 ? 1 : quality
  quality = quality > 100 ? 100 : quality
  maxSize = isNaN(maxSize) ? 1024 * 1024 * 1 : maxSize // 默认最大限制1MB
  plus.io.resolveLocalFileSystemURL(src, (entry) => { // 通过URL参数获取目录对象或文件对象
    entry.file((file) => { // 可通过entry对象操作图片
      if (file.size > maxSize) { // 如果大于200KB进行压缩
        // console.log('压缩前图片信息:' + JSON.stringify(file)); // 压缩前图片信息
        var pathCompress = '_doc/uniapp_temp/compressed/' + (Math.random() + '_compress.') + src.replace(/.+\./, '')
        let distPath = pathCompress
          .replace('.png', 'yasuo.png')
          .replace('.PNG', 'yasuo.PNG')
          .replace('.jpg', 'yasuo.jpg')
          .replace('.JPG', 'yasuo.JPG')
        // 获取图片宽高
        imager.getImageSize(src).then(res => {
          maxWidth = maxWidth || res.width
          maxHeight = maxHeight || res.height
          // 最佳比例
          let scale = imager.getScaleSize({
            imgWidth: res.width,
            imgHeight: res.height,
            containerWidth: maxWidth,
            containerHeight: maxHeight
          })
          plus.zip.compressImage({ // 5+ plus.zip.compressImage 了解一下，有详细的示例
            src: src, // src: 压缩原始图片的路径    
            dst: distPath, // dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个yasuo区分一下
            width: scale.width, // '100%'  // width, height: (String 类型 )缩放图片的宽度,高度
            height: scale.height, // '100%'
            quality: quality, // quality: (Number 类型 )压缩图片的质量
            overwrite: true, // overwrite: (Boolean 类型 )覆盖生成新文件
            // format:'jpg'   // format: (String 类型 )压缩转换后的图片格式
          }, (event) => {
            // 返回压缩后的图片路径
            translateApp({ src: distPath, quality: quality - 10, maxSize, maxWidth, maxHeight }, onsuccess, onerror)
          }, function(e) {
            onerror(e)
            loger.error(e)
          })
        })
      } else { // 小于200kb跳过压缩，直接返回现有的src
        var fileReader = new plus.io.FileReader()
        fileReader.readAsDataURL(file)
        fileReader.onloadend = function(e) {
          onsuccess(e.target.result)
        }
        fileReader.onerror = function(e) {
          onerror(e)
          loger.error(e)
        }
      }
    })
  }, (e) => { // 返回错误信息
    onerror(e)
    loger.error(e)
  })
}

/**
 * H5端图片压缩
 *  参数说明：
 *  src 图片url
 *  quality缩放比例 1-100
 *  type 返回图片类型  默认blob 
 *  callback 回调设置返回值 
*/
export function translateBrowser({ src, quality, type } = {}, onsuccess, onerror) {
  quality = quality || 68
  quality = quality / 100
  type = type || 'base64'
  var img = new Image()
  img.src = src
  img.onload = function() {
    var that = this
    var h = that.height // 默认按比例压缩
    var w = that.width
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')
    var width = document.createAttribute("width")
    width.nodeValue = w
    var height = document.createAttribute("height")
    height.nodeValue = h
    canvas.setAttributeNode(width)
    canvas.setAttributeNode(height)
    ctx.drawImage(that, 0, 0, w, h)
    var base64 = canvas.toDataURL('image/jpeg', quality) // 压缩比例
    canvas = null
    if (type === 'base64') {
      onsuccess(base64)
    } else {
      var blob = base64ToBlob(base64)
      var blobUrl = window.URL.createObjectURL(blob) // blob地址
      onsuccess(blobUrl)
    }
  }
  img.error = function (e) {
    onerror(e)
    loger.error(e)
  }
}

// base转Blob
export function base64ToBlob(base64) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	})
}

// 压缩
const compress = isPlus ? translateApp : translateBrowser

export {
  compress
}
